package com.projectpractice.controller;

import com.projectpractice.bean.Article;
import com.projectpractice.bean.User;
import com.projectpractice.service.UserService;
import com.projectpractice.common.utils.Result;
import com.projectpractice.common.utils.ResultEnum;
import com.projectpractice.common.utils.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * @RestController=@Controller+@ResponseBody
 * @Controller 用于表示控制器类
 * @ResponseBody 返回的对象结果会被转为Json格式数据
 * */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /* @RequestMapping 映射路径*/
    @RequestMapping("/doLogin")
    public Result login(User user){
        Result result=null;
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
//        if(rememberMe.orElse("off").equals("on")){
//            token.setRememberMe(true);
//        }

        SecurityUtils.getSubject().isPermitted("管理员");
        try {
            currentUser.login(token);
            result= ResultUtils.success(user);
        }catch (UnknownAccountException e){
            result=ResultUtils.success(user);
            result.setCode(ResultEnum.LOGIN_FAILS.getCode());
            result.setMsg(ResultEnum.LOGIN_FAILS.getMsg());
        }catch (IncorrectCredentialsException e){
            result=ResultUtils.success(user);
            result.setCode(ResultEnum.LOGIN_FAILS.getCode());
            result.setMsg(ResultEnum.LOGIN_FAILS.getMsg());
        }
        return result;
    }


    @RequestMapping("/toLogin")
    public ModelAndView toLogin(){
        System.out.println("进入登陆页面......");
        ModelAndView mv=new ModelAndView();
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("/toRegist")
    public ModelAndView toRegist(){
        System.out.println("进入注册页面......");
        ModelAndView mv=new ModelAndView();
        mv.setViewName("register");
        return mv;
    }

    @RequestMapping("/doRegist")
    public Result regist(User user){
        Result result=null;
        System.out.println("执行注册.....");
        user.setState(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        user.setCreatetime(dateFormat.format(new Date()));
        if(user.getRole()==null){
            user.setRole("学生");
        }
        System.out.println(user);
        User registUser=userService.regist(user);
        if(registUser!=null){
            result= ResultUtils.success(registUser);
        }
        else{
            result=ResultUtils.success(registUser);
            result.setCode(ResultEnum.LOGIN_FAILS.getCode());
            result.setMsg(ResultEnum.LOGIN_FAILS.getMsg());
        }
        return result;
    }


    @RequestMapping("/toForget")
    public ModelAndView toForget(){
        System.out.println("进入找回密码");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("forget");
        return modelAndView;
    }

    @RequestMapping("/doForget")
    public Result doForget(User u){
        Result result=null;
        System.out.println("执行找回.....");
        User user=new User();
        user.setName(u.getName());
        user.setEmail(u.getEmail());
        System.out.println(user);
        User forgetUser=userService.forget(user);
        if(forgetUser!=null){
            result= ResultUtils.success(forgetUser);
        }
        else{
            result=ResultUtils.success(forgetUser);
            result.setCode(ResultEnum.LOGIN_FAILS.getCode());
            result.setMsg(ResultEnum.LOGIN_FAILS.getMsg());
        }
        return result;
    }

    @RequestMapping("/logout")
    public ModelAndView logout() {
        ModelAndView mv = new ModelAndView();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println("用户是否登录：" + subject.isAuthenticated());
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("/toPassword/{id}")
    public ModelAndView toPassword(@PathVariable Integer id){
        ModelAndView mv=new ModelAndView();
        //设置视图
        mv.setViewName("change_password");
        User user=userService.getUserById(id);
        //设置数据
        mv.addObject("user",user);

        return mv;
    }

    @RequestMapping("/doPassword")
    public Result doPassword(User user){
        Result result=null;
        // 先获取原来对象的值
        User u=userService.getUserById(user.getId());
        u.setPassword(user.getPassword());
        System.out.println(u);
        int data=userService.update(u);
        result=ResultUtils.success(data);
        if(data>0){
            result.setCode(0);
            result.setMsg("更新成功");
        }
        else{
            result.setMsg("更新失败");
        }
        return result;
    }

    @RequestMapping("/list")
    public ModelAndView toList(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("user_list");
        return mv;
    }

    @RequestMapping("/toAdd")
    public ModelAndView toAdd(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("user_add");
        return mv;
    }

    @RequestMapping("/doAdd")
    public Result doAdd(User user){
        user.setState(1);
        User registUser=userService.regist(user);
        System.out.println("添加数据["+user+"]");
        Result result=ResultUtils.success(registUser);
        result.setMsg("添加成功");
        return result;
    }

    @RequestMapping("/getUsers")
    public Result getUsers(){
        List<User> list=userService.list();
        Result result=ResultUtils.success(list);
        result.setCode(0);
        result.setMsg("查询成功");
        return result;
    }

    @RequestMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id){
        Result result=null;
        int data=userService.delete(id);
        result=ResultUtils.success(data);
        if(data>0){
            result.setCode(0);
            result.setMsg("删除成功");
        }
        else{
            result.setMsg("删除失败");
        }
        return result;
    }

    @RequestMapping("/toEdit/{id}")
    public ModelAndView toEdit(@PathVariable Integer id){
        ModelAndView mv=new ModelAndView();
        //设置视图
        mv.setViewName("user_edit");
        User user=userService.getUserById(id);
        //设置数据
        mv.addObject("user",user);
        mv.addObject("url","/user/"+user.getHeadpic());

        return mv;
    }

    @RequestMapping("/edit")
    public Result edit(User user){
        Result result=null;
        // 先获取原来对象的值
        System.out.println(user);
        User u=userService.getUserById(user.getId());
        u.setName(user.getName());
        u.setHeadpic(user.getHeadpic());
        u.setEmail(user.getEmail());
        u.setPassword(user.getPassword());
        u.setSex(user.getSex());
        u.setRole(user.getRole());
        int data=userService.update(u);
        result=ResultUtils.success(data);
        if(data>0){
            result.setCode(0);
            result.setMsg("更新成功");
        }
        else{
            result.setMsg("更新失败");
        }
        return result;
    }

    @RequestMapping("/uploadHeadPic")
    public Result uploadHeadPic(@RequestParam("file") MultipartFile file) throws IOException {
        // 项目路径
        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
        System.out.println("projectPath="+projectPath);
        // 绝对路径=项目路径+自定义路径
        File upload = new File(projectPath.getAbsolutePath(), "static/user/");
        if (!upload.exists())
            upload.mkdirs();
        Result result=null;
        if (file.isEmpty()) {
            result=ResultUtils.error(-1,"上传失败");
        }
        else{
            //获取文件名称
            String fileName=file.getOriginalFilename();
            System.out.println("dest="+upload.getAbsolutePath()+"\\"+fileName);
            File dest=new File(upload.getAbsolutePath()+"\\"+fileName);
            //文件IO
            file.transferTo(dest);
            result=ResultUtils.success();
            result.setCode(0);
            result.setMsg("上传成功");
            Map<String,String> map=new HashMap<>();
            map.put("src",fileName);
            result.setData(map);
        }

        return result;
    }

    @RequestMapping("/toDetail/{id}")
    public ModelAndView toDetail(@PathVariable Integer id){
        ModelAndView mv=new ModelAndView();
        //设置视图
        mv.setViewName("user_detail");
        User user=userService.getUserById(id);
        //设置数据
        mv.addObject("user",user);
        mv.addObject("url","/user/"+user.getHeadpic());

        return mv;
    }

    @RequestMapping("/state/{id}")
    public Result state(@PathVariable Integer id){
        Result result=null;
        // 先获取原来对象的值
        User u=userService.getUserById(id);
        u.setState(Math.abs(u.getState()-1));
        System.out.println(u);
        int data=userService.update(u);
        result=ResultUtils.success(data);
        if(data>0){
            result.setCode(0);
            result.setMsg("更新成功");
        }
        else{
            result.setMsg("更新失败");
        }
        return result;
    }

    @RequestMapping("/admintoAdd")
    public ModelAndView admintoAdd(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("admin_add");
        return mv;
    }

    @RequestMapping("/admindoAdd")
    public Result admindoAdd(User user){
        user.setState(1);
        User registUser=userService.regist(user);
        System.out.println("添加数据["+user+"]");
        Result result=ResultUtils.success(registUser);
        result.setMsg("添加成功");
        return result;
    }

    @RequestMapping("/adminlist")
    public ModelAndView adminList(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("admin_list");
        return mv;
    }

    @RequestMapping("/getAdmins")
    public Result getAdmins(){
        List<User> list=userService.list();
        System.out.println(list);
        Iterator<User> iterator = list.iterator();
        while (iterator.hasNext()) {
            User user = iterator.next();
            if ("student".equals(user.getRole())) {
                iterator.remove();//使用迭代器的删除方法删除
            }
            if ("teacher".equals(user.getRole())) {
                iterator.remove();//使用迭代器的删除方法删除
            }
        }
        System.out.println(list);
        Result result=ResultUtils.success(list);
        result.setCode(0);
        result.setMsg("查询管理员成功");
        return result;
    }

    @RequestMapping("/portal_login")
    public ModelAndView toIndex(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("portal_login");
        return mv;
    }
//    @RequestMapping("/admintoDetail/{id}")
//    public ModelAndView admintoDetail(@PathVariable Integer id){
//        ModelAndView mv=new ModelAndView();
//        //设置视图
//        mv.setViewName("admin_detail");
//        User user=userService.getUserById(id);
//        //设置数据
//        mv.addObject("user",user);
//        mv.addObject("url","/user/"+user.getHeadpic());
//
//        return mv;
//    }
//    @RequestMapping("/admintoEdit/{id}")
//    public ModelAndView admintoEdit(@PathVariable Integer id){
//        ModelAndView mv=new ModelAndView();
//        //设置视图
//        mv.setViewName("admin_edit");
//        User user=userService.getUserById(id);
//        //设置数据
//        mv.addObject("user",user);
//        mv.addObject("url","/user/"+user.getHeadpic());
//
//        return mv;
//    }

}
